package cn.edu.zafu.bigdata.yeshuchang.wlbc;
import java.io.*;
import java.net.*;

public class TimeServer {
    public static void main(String[] args) {
        int port = 12345; // 服务端端口号
        try {
            DatagramSocket serverSocket = new DatagramSocket(port);
            System.out.println("Time server is running and waiting for client requests...");

            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];

            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());

                String currentTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
                System.out.println("Request from " + receivePacket.getAddress().toString() + ": " + sentence);

                String response = "Current Time: " + currentTime;
                sendData = response.getBytes();

                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
                serverSocket.send(sendPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}